package com.cmas.platform.service.impl;

import java.util.Date;
import java.util.List;

import com.aidex.common.constant.Constants;
import com.aidex.common.core.domain.entity.SysRole;
import com.aidex.common.core.domain.model.LoginUser;
import com.aidex.common.utils.DateUtils;
import com.aidex.common.utils.ObjectUtils;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.system.mapper.SysUserRoleMapper;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.cmas.platform.domain.*;
import com.cmas.platform.domain.em.ApproveStatusEnum;
import com.cmas.platform.domain.em.NotificationTypeEnum;
import com.cmas.platform.domain.em.SystemNotificationTypeEnum;
import com.cmas.platform.mapper.ApproveRecordMapper;
import com.cmas.platform.mapper.RegionMapper;
import com.cmas.platform.vo.OperatorApplyVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aidex.common.core.domain.BaseEntity;
import com.aidex.common.utils.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmas.platform.mapper.OperatorApplyMapper;
import com.cmas.platform.service.OperatorApplyService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 运营申请表Service业务层处理
 *
 * @author su
 * @email 1218819874@qq.com
 * @date 2024-06-01
 */
@Service
public class OperatorApplyServiceImpl extends ServiceImpl<OperatorApplyMapper, OperatorApply> implements OperatorApplyService {

    private static final Logger log = LoggerFactory.getLogger(OperatorApplyServiceImpl.class);

    @Autowired
    private ApproveRecordMapper approveRecordMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 查询运营申请表列表
     *
     * @param operatorApply 运营申请表
     * @return 运营申请表
     */
    @Override
    public List<OperatorApply> selectOperatorApplyList(OperatorApply operatorApply) {
        return baseMapper.selectList(setQueryWrapper(operatorApply));
    }

    @Override
    public List<OperatorApplyVo> selectOperatorApplyVoList(OperatorApply operatorApply) {
        return baseMapper.selectOperatorApplyVoList(setQueryWrapper(operatorApply));
    }


    public QueryWrapper<OperatorApply> setQueryWrapper(OperatorApply operatorApply) {
        QueryWrapper<OperatorApply> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(operatorApply.getId())) {
            queryWrapper.eq("operator_apply.id", operatorApply.getId());
        }
        if (StringUtils.isNotEmpty(operatorApply.getUserId())) {
            queryWrapper.eq("operator_apply.user_id", operatorApply.getUserId());
        }
        if (StringUtils.isNotEmpty(operatorApply.getStatus())) {
            queryWrapper.eq("operator_apply.status", operatorApply.getStatus());
        }
        return queryWrapper;
    }


    /**
     * 批量删除运营申请表
     *
     * @param ids 需要删除的运营申请表ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteOperatorApplyByIds(String[] ids) {
        return baseMapper.deleteOperatorApplyByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approve(ApproveRecord approveRecord) {
        OperatorApply operatorApply = baseMapper.selectById(approveRecord.getItemId());
        approveRecord.setItemTableName(SqlHelper.table(OperatorApply.class).getTableName());
        approveRecord.setBeforeStatus(operatorApply.getStatus());
        SysRole userRole = baseMapper.selectUserRole(operatorApply.getUserId());
        String roleKey = null;
        if (approveRecord.getType().equals("0")) {
            if (userRole == null || !userRole.getRoleKey().equals("operatorUser")) {
                roleKey = "operatorUser";
            }
            //设置地区
            Region region = regionMapper.selectOne(new QueryWrapper<Region>()
                    .lambda().eq(Region::getUserId, operatorApply.getUserId()));
            if (ObjectUtils.isEmpty(region)) {
                region = new Region();
                region.setUserId(operatorApply.getUserId());
                regionMapper.insert(region);
            }
            operatorApply.setStatus(ApproveStatusEnum.ARTIFICIAL_PASS.getValue());
        } else if (approveRecord.getType().equals("1")) {
            if (!userRole.getRoleKey().equals("ordinaryUser")) {
                roleKey = "ordinaryUser";
            }
            regionMapper.delete(new QueryWrapper<Region>()
                    .lambda().eq(Region::getUserId, operatorApply.getUserId()));
            operatorApply.setStatus(ApproveStatusEnum.ARTIFICIAL_REJECT.getValue());
        }
        //修改用户角色
        if (StringUtils.isNotEmpty(roleKey)) {
            SysRole operatorUser = baseMapper.selectRoleByRoleKey(roleKey);
            sysUserRoleMapper.deleteUserRoleByUserId(operatorApply.getUserId());
            baseMapper.saveUserRole(operatorApply.getUserId(), operatorUser.getId());
        }
        baseMapper.updateById(operatorApply);
        approveRecord.setAfterStatus(operatorApply.getStatus());
        approveRecordMapper.insert(approveRecord);
        //发送消息
        sendMessage(operatorApply);
    }


    public void sendMessage(OperatorApply operatorApply) {
        JSONObject message = new JSONObject();
        message.put("userId", operatorApply.getUserId());
        message.put("status", operatorApply.getStatus());
        message.put("systemType", SystemNotificationTypeEnum.OPERATOR_APPLY.getValue());
        message.put("type", NotificationTypeEnum.SYSTEM.getValue());
        rabbitTemplate.convertAndSend(Constants.NOTICE_EXCHANGE, Constants.NOTICE_QUEUE_ROUTING_KEY, message.toString());
    }


    /**
     * 保存运营申请
     *
     * @param operatorApply
     * @return
     */
    @Override
    public OperatorApply saveOperatorApply(OperatorApply operatorApply) {
        operatorApply.setStatus(ApproveStatusEnum.ARTIFICIAL_AUDIT.getValue());
        return operatorApply;
    }

    /**
     * 修改运营申请
     *
     * @param operatorApply
     * @return
     */
    @Override
    public int updateOperatorApply(OperatorApply operatorApply) {
        operatorApply.setStatus(ApproveStatusEnum.ARTIFICIAL_AUDIT.getValue());
        return baseMapper.updateById(operatorApply);
    }

    @Override
    public boolean apply() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        boolean insertFlag = isInsertOperationApply();
        if (insertFlag) {
            OperatorApply operatorApply = new OperatorApply();
            operatorApply.setUserId(loginUser.getUserId());
            operatorApply.setStatus(ApproveStatusEnum.ARTIFICIAL_AUDIT.getValue());
            baseMapper.insert(operatorApply);
            return true;
        }
        return false;
    }


    private boolean isInsertOperationApply() {
        int days = remainingOperatorApplyTime();
        boolean insertFlag = false;
        if (days <= 0) {
            insertFlag = true;
        }
        return insertFlag;

    }


    public int remainingOperatorApplyTime() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        OperatorApply old = baseMapper.selectLastOperatorApply(loginUser.getUserId());
        int days = 0;
        if (ObjectUtils.isNotEmpty(old)) {
            if (old.getStatus().equals(ApproveStatusEnum
                    .ARTIFICIAL_AUDIT.getValue())) {
                //还有申请未审核
                days = 99999;
            } else {
                days = 30 - DateUtils.differentDaysByMillisecond(old.getCreateTime()
                        , DateUtils.getNowDate());
            }
        }
        return days;
    }


}
